package com.dxd.onlineshop.controller;

import com.dxd.onlineshop.pojo.Order;
import com.dxd.onlineshop.pojo.OrderItem;
import com.dxd.onlineshop.pojo.Result;
import com.dxd.onlineshop.service.OrderService;
import com.dxd.onlineshop.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
public class OrderController {

    @Autowired
    private final OrderService orderService;

    //创建订单
    @PostMapping
    public Result<Order> createOrder(@RequestBody CreateOrderRequest request) {
        try {
            Order order = orderService.createOrder(request.getUserId(), request.getOrderItems());
            return Result.success(order);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建订单失败");
        }
    }

    //获取订单信息(通过用户ID)
    @GetMapping("/user/{userId}")
    public Result<List<Order>> getUserOrders(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            List<Order> orders = orderService.getUserOrders(userId);
            System.out.println("从数据库获取到用户订单信息:" + orders);
            return Result.success(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("Failed to retrieve user orders information: " + e.getMessage());
        }
    }

    //获取订单信息(通过订单ID)
    @GetMapping("/{orderId}")
    public Result<Order> getOrderById(@PathVariable Integer orderId) {
        Order order = orderService.getOrderById(orderId);
        return order != null ? Result.success(order) : Result.error("订单不存在");
    }

    //修改订单状态
    @PutMapping("/{orderId}/status")
    public Result<Boolean> updateOrderStatus(@PathVariable Integer orderId, @RequestBody UpdateOrderStatusRequest request) {
        boolean updated = orderService.updateOrderStatus(orderId, request.getNewStatus());
        return updated ? Result.success(true) : Result.error("更新订单状态失败");
    }

    //取消订单
    @PostMapping("/{orderId}/cancel")
    public Result<Boolean> cancelOrder(@PathVariable Integer orderId) {
        boolean cancelled = orderService.cancelOrder(orderId);
        return cancelled ? Result.success(true) : Result.error("取消订单失败");
    }

    //删除订单
    @DeleteMapping("/{orderId}")
    public Result deleteOrder(@PathVariable Integer orderId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            // 解析 token 获取用户 ID
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");

            // 获取订单信息
            Order order = orderService.getOrderById(orderId);

            // 检查订单是否存在且属于当前用户
            if (order == null) {
                return Result.error("订单不存在");
            }
            if (!order.getUserId().equals(userId)) {
                return Result.error("无权删除此订单");
            }

            // 调用 service 层方法删除订单
            boolean deleted = orderService.deleteOrder(orderId);

            if (deleted) {
                return Result.success();
            } else {
                return Result.error("订单删除失败，可能是因为订单状态不允许删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除订单时发生错误: " + e.getMessage());
        }
    }


    //获取用户的订单统计(总金额，总订单数)
    @GetMapping("/statistics/{userId}")
    public Result<OrderService.OrderStatistics> getOrderStatistics(@PathVariable Integer userId) {
        OrderService.OrderStatistics statistics = orderService.getOrderStatistics(userId);
        return Result.success(statistics);
    }

    //内部类，创建订单时使用
    @Data
    private static class CreateOrderRequest {
        private Integer userId; //创建订单的用户
        private List<OrderItem> orderItems; //订单所有的商品
    }

    //内部类，更新订单状态时使用
    @Data
    private static class UpdateOrderStatusRequest {
        private Order.OrderStatus newStatus;  //从Order类的枚举中获取一个新的订单状态
    }
}